package com.example.mr5.money.main.userdefined;

import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mr5.money.R;
import com.example.mr5.money.constant.Constant;
import com.example.mr5.money.main.myincome.FilterGridViewAdapter;
import com.example.mr5.money.model.CommonType;
import com.example.mr5.money.util.DatabaseHelper;
import com.example.mr5.money.view.Segment;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;

/**
 * Created by Mr.5
 * Date：2016/9/11.
 * Time：22:35
 */
public class UserDefinedFragment extends Fragment implements Segment.OnSegmentSelectedListener, View.OnClickListener, ExpandableListView.OnChildClickListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
    private Segment segment;
    private List<String> titles;
    private ExpandableListView refreshExpandableListView;
    private UserDefinedListAdapter adapter;
    private List<CommonType> parentList;
    private List<CommonType> childList;
    private ImageView parentAdd;
    private AlertDialog dialog;
    private Window window;
    private PopupWindow popupWindow;
    private List<CommonType> list1, list2, list3, list4, list5;
    private int[] arrayId = new int[]{R.array.yi, R.array.shi, R.array.zhu, R.array.xing};
    private String[] arrayParentName = new String[]{"衣", "食", "住", "行", "其他"};
    private List<List> listList = new ArrayList<>();
    private List<FilterGridViewAdapter> adapterList;
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
    private String preferenceString;
    private final static String OTHER = "other";
    private DatabaseHelper databaseHelper;
    private SQLiteDatabase db;
    private ProgressBar progressBar;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        preferences = getActivity().getSharedPreferences("other_expense", Context.MODE_PRIVATE);
        preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        editor = preferences.edit();
        databaseHelper = DatabaseHelper.getDBInstance(getContext());
        db = databaseHelper.getWritableDatabase();
        initData();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(getContext(), R.layout.fragment_user_defined, null);
        progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
        parentAdd = (ImageView) view.findViewById(R.id.parent_add);
        parentAdd.setOnClickListener(this);
        segment = (Segment) view.findViewById(R.id.segment);
        segment.setTitles(titles);
        segment.setOnSegmentSelectedListener(this);
        refreshExpandableListView = (ExpandableListView) view.findViewById(R.id.user_defined_list);
        refreshExpandableListView.setGroupIndicator(null);
        adapter = new UserDefinedListAdapter(getContext(), parentList, childList);
        refreshExpandableListView.setAdapter(adapter);
        refreshExpandableListView.setOnChildClickListener(this);
        refreshExpandableListView.setOnItemLongClickListener(this);
        return view;
    }

    private void initData() {
        parentList = new ArrayList<>();
        childList = new ArrayList<>();
        loadIncomeDataFromDB();

        titles = new ArrayList<>();
        titles.add("收入");
        titles.add("支出");

        dialog = new AlertDialog.Builder(getContext()).create();
        window = dialog.getWindow();

//        preferenceSet = new HashSet<>();
        adapterList = new ArrayList<>();
        list1 = new ArrayList<>();
        list2 = new ArrayList<>();
        list3 = new ArrayList<>();
        list4 = new ArrayList<>();
        list5 = new ArrayList<>();
        listList.add(list1);
        listList.add(list2);
        listList.add(list3);
        listList.add(list4);
        listList.add(list5);
        loadDataFromArray();
        loadDataFromPreference();
        adapterList.add(new FilterGridViewAdapter(getContext(), list1));
        adapterList.add(new FilterGridViewAdapter(getContext(), list2));
        adapterList.add(new FilterGridViewAdapter(getContext(), list3));
        adapterList.add(new FilterGridViewAdapter(getContext(), list4));
        adapterList.add(new FilterGridViewAdapter(getContext(), list5));
    }

    private void loadDataFromArray() {
        for (int i = 0; i < arrayId.length; i++) {
            listList.get(i).clear();
            String[] temp = getResources().getStringArray(arrayId[i]);
            CommonType commonType = null;
            for (int j = 0; j < temp.length; j++) {
                commonType = new CommonType();
                commonType.setParentName(arrayParentName[i]);
                commonType.setName(temp[j]);
                listList.get(i).add(commonType);
            }
        }
    }

    private void loadDataFromPreference() {
        list5.clear();
        preferenceString = preferences.getString(OTHER, null);
        if (preferenceString != null) {
            Log.d("555log", "preferenceString:" + preferenceString + preferenceString.length());
        }

        CommonType commonType;
        if (preferenceString != null) {
//            Iterator<String> iterator = preferenceSet.iterator();
            if (preferenceString.indexOf("@") < 0) {//只有一个元素
                commonType = new CommonType();
                commonType.setParentName("其他");
                commonType.setName(preferenceString);
                list5.add(commonType);
            } else {
                String[] otherItem = preferenceString.split("@");
                for (int i = 0; i < otherItem.length; i++) {
                    commonType = new CommonType();
                    commonType.setParentName("其他");
                    commonType.setName(otherItem[i]);
                    list5.add(commonType);
                }
            }
        }
        CommonType commonType1 = new CommonType();
        commonType1.setName("添加");
        commonType1.setParentName("其他");
        commonType1.setIsCheck(true);
        list5.add(commonType1);
    }

    private void loadExpenseDataFromDB() {
        parentList.clear();
        childList.clear();
        CommonType commonType1;
        CommonType commonType2;
        ArrayList<CommonType> childListTemp;

        Cursor cursor1 = db.query(Constant.DATABASE_EXPENSE_FIRST_TABLE_NAME, null, null, null, null, null, null, null);
        while (cursor1.moveToNext()) {
            commonType1 = new CommonType();
            childListTemp = new ArrayList<>();
            String firstTitle = cursor1.getString(cursor1.getColumnIndex(Constant.DATABASE_EXPENSE_FIRST_TABLE_FIELD_TITLE));
            commonType1.setName(firstTitle);
            Cursor cursor2 = db.query(Constant.DATABASE_EXPENSE_SECOND_TABLE_NAME, null,
                    Constant.DATABASE_EXPENSE_SECOND_TABLE_FIELD_FIRST_TITLE + "= ?", new String[]{commonType1.getName()}, null, null, null);
            while (cursor2.moveToNext()) {
                commonType2 = new CommonType();
                String secondTitle = cursor2.getString(cursor2.getColumnIndex(Constant.DATABASE_EXPENSE_SECOND_TABLE_FIELD_TITLE));
                String parentTitle = cursor2.getString(cursor2.getColumnIndex(Constant.DATABASE_EXPENSE_SECOND_TABLE_FIELD_FIRST_TITLE));
                commonType2.setName(secondTitle);
                commonType2.setParentName(parentTitle);
                childListTemp.add(commonType2);
            }
//            childListTemp.add(null);
            cursor2.close();
            commonType1.setChildrenList(childListTemp);
            parentList.add(commonType1);
        }
        cursor1.close();

        if (parentList.size() > 0 && parentList.get(0).getChildrenList() != null) {
            childList.addAll(parentList.get(0).getChildrenList());
        }
    }

    private void loadIncomeDataFromDB() {
        parentList.clear();
        childList.clear();
        CommonType commonType1;
        CommonType commonType2;
        ArrayList<CommonType> childListTemp;

        Cursor cursor1 = db.query(Constant.DATABASE_INCOME_FIRST_TABLE_NAME, null, null, null, null, null, null, null);
        while (cursor1.moveToNext()) {
            commonType1 = new CommonType();
            childListTemp = new ArrayList<>();
            String firstTitle = cursor1.getString(cursor1.getColumnIndex(Constant.DATABASE_INCOME_FIRST_TABLE_FIELD_TITLE));
            commonType1.setName(firstTitle);
            Cursor cursor2 = db.query(Constant.DATABASE_INCOME_SECOND_TABLE_NAME, null,
                    Constant.DATABASE_INCOME_SECOND_TABLE_FIELD_FIRST_TITLE + "= ?", new String[]{commonType1.getName()}, null, null, null);
            while (cursor2.moveToNext()) {
                commonType2 = new CommonType();
                String secondTitle = cursor2.getString(cursor2.getColumnIndex(Constant.DATABASE_INCOME_SECOND_TABLE_FIELD_TITLE));
                String parentTitle = cursor2.getString(cursor2.getColumnIndex(Constant.DATABASE_INCOME_SECOND_TABLE_FIELD_FIRST_TITLE));
                commonType2.setName(secondTitle);
                commonType2.setParentName(parentTitle);
                childListTemp.add(commonType2);
            }
            childListTemp.add(null);
            cursor2.close();
            commonType1.setChildrenList(childListTemp);
            parentList.add(commonType1);
        }
        cursor1.close();

        if (parentList.size() > 0 && parentList.get(0).getChildrenList() != null) {
            childList.addAll(parentList.get(0).getChildrenList());
        }
    }


    @Override
    public void onSegmentSelected(int index) {
        if (index == 0) {
            loadIncomeDataFromDB();
        } else {
            loadExpenseDataFromDB();
        }
        adapter.notifyDataSetChanged();
    }

    public UserDefinedListAdapter getAdapter() {
        return adapter;
    }

    public void setEditable(boolean editable) {
        if (editable) {
            parentAdd.setVisibility(View.VISIBLE);
        } else {
            parentAdd.setVisibility(View.GONE);
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        Log.d(Constant.TAG, "UserDefinedFragment onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(Constant.TAG, "UserDefinedFragment onPause");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.parent_add:
                if (segment.getSelectedIndex() == 0) {
                    showInsertDialog(0, true);//insert parent item
                } else {
                    showPopupWindow();
                }
                break;
            case R.id.text_confirm:
                insertExpense();
                popupWindow.dismiss();
//                onSegmentSelected(1);
                break;
//            case R.id.text_add:
//                popupWindow.dismiss();
//                showInsertDialog(0, true);
//                break;
        }
    }

    @Override
    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
        if (getAdapter().getEditable()) {
            if (segment.getSelectedIndex() == 0) {
                if (childPosition != parentList.get(groupPosition).getChildrenList().size() - 1) {
                    showDeleteChildDialog(groupPosition, childPosition);
                } else {
                    showInsertDialog(groupPosition, false);//insert child item
                }
            } else {
                showDeleteChildDialog(groupPosition, childPosition);
            }

        }
        return false;
    }

    private void insertExpense() {
        boolean isItemExist = false;
        Cursor cursor = db.query(Constant.DATABASE_EXPENSE_SECOND_TABLE_NAME, null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            for (int i = 0; i < arrayParentName.length; i++) {
                for (int j = 0; j < listList.get(i).size(); j++) {
                    CommonType commonType = (CommonType) listList.get(i).get(j);
                    if (commonType.isCheck()) {
                        if (commonType.getName().equals(cursor.getString(cursor.getColumnIndex(Constant.DATABASE_EXPENSE_SECOND_TABLE_FIELD_TITLE)))
                                && commonType.getParentName().equals(cursor.getString(cursor.getColumnIndex(Constant.DATABASE_EXPENSE_SECOND_TABLE_FIELD_FIRST_TITLE)))) {
                            commonType.setIsCheck(false);
                            isItemExist = true;
                        }
                    }
                }
            }
        }
        cursor.close();
        List<String> oldFirstTitles = new ArrayList<>();
        for (int m = 0; m < parentList.size(); m++) {
            oldFirstTitles.add(parentList.get(m).getName());
        }
        List<String> newAddFirstTitles = new ArrayList<>();
        boolean isInserted = false;
        for (int i = 0; i < arrayParentName.length; i++) {
            for (int j = 0; j < listList.get(i).size(); j++) {
                CommonType commonType = (CommonType) listList.get(i).get(j);
                if (commonType.isCheck() && !commonType.getName().equals("添加")) {
                    ContentValues values = new ContentValues();
                    values.put(Constant.DATABASE_EXPENSE_SECOND_TABLE_FIELD_FIRST_TITLE, commonType.getParentName());
                    values.put(Constant.DATABASE_EXPENSE_SECOND_TABLE_FIELD_TITLE, commonType.getName());
                    db.insert(Constant.DATABASE_EXPENSE_SECOND_TABLE_NAME, null, values);
                    isInserted = true;
                    if (!oldFirstTitles.contains(commonType.getParentName())) {
                        newAddFirstTitles.add(commonType.getParentName());
                        oldFirstTitles.add(commonType.getParentName());
                    }
                }
            }
        }
        if (newAddFirstTitles != null) {
            for (int n = 0; n < newAddFirstTitles.size(); n++) {
                ContentValues values = new ContentValues();
                values.put(Constant.DATABASE_EXPENSE_FIRST_TABLE_FIELD_TITLE, newAddFirstTitles.get(n));
                db.insert(Constant.DATABASE_EXPENSE_FIRST_TABLE_NAME, null, values);
            }
        }
        if (isInserted && isItemExist) {
//            Toast.makeText(getContext(), "添加成功,已存在条目不再添加", Toast.LENGTH_LONG).show();
            toastMsg = "添加成功,已存在条目不再添加";
            createThread().start();
        } else if (isInserted) {
            toastMsg = "添加成功";
            createThread().start();
//            Toast.makeText(getContext(), "添加成功", Toast.LENGTH_LONG).show();
        } else if (isItemExist) {
            Toast.makeText(getContext(), "所选条目已存在", Toast.LENGTH_LONG).show();
        }
    }

    private void showPopupWindow() {
        loadDataFromArray();
        loadDataFromPreference();
        backgroundAlpha(0.5f);//让背景变暗
        View popupWindow_view = getActivity().getLayoutInflater().inflate(R.layout.popupwindow_add_item, null, false);
        TextView confirm = (TextView) popupWindow_view.findViewById(R.id.text_confirm);
        confirm.setOnClickListener(this);
        GridView g1 = (GridView) popupWindow_view.findViewById(R.id.g1);//衣
        GridView g2 = (GridView) popupWindow_view.findViewById(R.id.g2);//食
        GridView g3 = (GridView) popupWindow_view.findViewById(R.id.g3);//住
        GridView g4 = (GridView) popupWindow_view.findViewById(R.id.g4);//行
        GridView g5 = (GridView) popupWindow_view.findViewById(R.id.g5);//其他

        g1.setAdapter(adapterList.get(0));
        g2.setAdapter(adapterList.get(1));
        g3.setAdapter(adapterList.get(2));
        g4.setAdapter(adapterList.get(3));
        g5.setAdapter(adapterList.get(4));
        g1.setOnItemClickListener(this);
        g2.setOnItemClickListener(this);
        g3.setOnItemClickListener(this);
        g4.setOnItemClickListener(this);
        g5.setOnItemClickListener(this);
//        TextView add = (TextView) popupWindow_view.findViewById(R.id.text_add);
//        add.setOnClickListener(this);

        popupWindow = new PopupWindow(popupWindow_view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setAnimationStyle(R.style.popWindowAnimation);//设置弹出和消失的动画
        popupWindow.setFocusable(true);// 取得焦点
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.showAtLocation(popupWindow_view, Gravity.BOTTOM, 0, 0);
        // 点击窗体内其他地方消失
        popupWindow_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if (popupWindow != null && popupWindow.isShowing()) {
                    backgroundAlpha(1);
                    popupWindow.dismiss();
                }
                return false;
            }
        });

        //设置消失的监听
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                popupWindow = null;
                backgroundAlpha(1);
            }
        });
    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getActivity().getWindow().setAttributes(lp);
    }


    private void showDeleteChildDialog(final int groupPosition, final int childPosition) {
        dialog.show();
        window.setContentView(R.layout.dialog_delete_item);
        final TextView deleteContent = (TextView) window.findViewById(R.id.delete_content);
        deleteContent.setText(parentList.get(groupPosition).getName() + "-" + parentList.get(groupPosition).getChildrenList().get(childPosition).getName());
        final Button confirm = (Button) window.findViewById(R.id.confirm);
        final Button cancel = (Button) window.findViewById(R.id.cancel);

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                db.delete(segment.getSelectedIndex() == 0 ? Constant.DATABASE_INCOME_SECOND_TABLE_NAME : Constant.DATABASE_EXPENSE_SECOND_TABLE_NAME,
                        "title = ? and first_title = ?",
                        new String[]{parentList.get(groupPosition).getChildrenList().get(childPosition).getName(), parentList.get(groupPosition).getName()});
                dialog.dismiss();
                toastMsg = "删除成功！";
                createThread().start();
//                Toast.makeText(getContext(), "删除成功！", Toast.LENGTH_LONG).show();
//                onSegmentSelected(segment.getSelectedIndex());
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    private void showInsertDialog(final int groupPosition, final boolean isParentItem) {
        dialog.setView(new EditText(getContext()));
        dialog.show();
        window.setContentView(R.layout.dialog_insert_item);
        final TextView insertFirstTitle = (TextView) window.findViewById(R.id.insert_first_title);
        final EditText insertContent = (EditText) window.findViewById(R.id.insert_content);
        if (isParentItem) {
            insertFirstTitle.setText(segment.getTitle(segment.getSelectedIndex()) + ":");
        } else {
            if (groupPosition == -1) {
                insertFirstTitle.setText("其他 -");
            } else {
                insertFirstTitle.setText(parentList.get(groupPosition).getName() + " -");
            }
        }
        final Button confirm = (Button) window.findViewById(R.id.confirm);
        final Button cancel = (Button) window.findViewById(R.id.cancel);

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(insertContent.getText().toString())) {
                    ContentValues values = new ContentValues();
                    if (isParentItem) {
                        Cursor cursor = db.query(segment.getSelectedIndex() == 0 ? Constant.DATABASE_INCOME_FIRST_TABLE_NAME : Constant.DATABASE_EXPENSE_FIRST_TABLE_NAME,
                                null, null, null, null, null, null);
                        boolean isExist = false;
                        while (cursor.moveToNext()) {
                            if (insertContent.getText().toString().equals(cursor.getString(cursor.getColumnIndex("title")))) {
                                isExist = true;
                            }
                        }
                        if (!isExist) {
                            values.put("title", insertContent.getText().toString());
                            db.insert(segment.getSelectedIndex() == 0 ? Constant.DATABASE_INCOME_FIRST_TABLE_NAME : Constant.DATABASE_EXPENSE_FIRST_TABLE_NAME,
                                    null, values);
//                            Toast.makeText(getContext(), "添加成功！", Toast.LENGTH_LONG).show();
//                            onSegmentSelected(segment.getSelectedIndex());
                            toastMsg = "添加成功！";
                            createThread().start();
                        } else {
                            Toast.makeText(getContext(), "该条目已经存在！", Toast.LENGTH_LONG).show();

                        }
                    } else {
                        Cursor cursor = db.query(segment.getSelectedIndex() == 0 ? Constant.DATABASE_INCOME_SECOND_TABLE_NAME : Constant.DATABASE_EXPENSE_SECOND_TABLE_NAME,
                                null, null, null, null, null, null);
                        boolean isExist = false;
                        if (groupPosition == -1) {
                            while (cursor.moveToNext()) {
                                if (cursor.getString(cursor.getColumnIndex("first_title")).equals("其他")
                                        && insertContent.getText().toString().equals(cursor.getString(cursor.getColumnIndex("title")))) {
                                    isExist = true;
                                }
                            }
                            if (!isExist) {
                                values.put("first_title", "其他");
                                values.put("title", insertContent.getText().toString());
                                db.insert(Constant.DATABASE_EXPENSE_SECOND_TABLE_NAME, null, values);
                                Cursor cursor1 = db.query(Constant.DATABASE_EXPENSE_FIRST_TABLE_NAME, null, null, null, null, null, null);
                                boolean isOtherExist = false;
                                while (cursor1.moveToNext()) {
                                    if (cursor1.getString(cursor1.getColumnIndex(Constant.DATABASE_EXPENSE_FIRST_TABLE_FIELD_TITLE))
                                            .equals("其他")) {
                                        isOtherExist = true;
                                    }
                                }
                                if (!isOtherExist) {
                                    ContentValues values1 = new ContentValues();
                                    values1.put(Constant.DATABASE_EXPENSE_FIRST_TABLE_FIELD_TITLE, "其他");
                                    db.insert(Constant.DATABASE_EXPENSE_FIRST_TABLE_NAME, null, values1);
                                }
                                if (preferenceString == null) {
                                    preferenceString = insertContent.getText().toString();
                                } else {
                                    preferenceString += ("@" + insertContent.getText().toString());
                                }
                                editor.putString(OTHER, preferenceString);
                                editor.commit();
                                toastMsg = "添加成功！";
                                createThread().start();
//                                Toast.makeText(getContext(), "添加成功！", Toast.LENGTH_LONG).show();
//                                onSegmentSelected(segment.getSelectedIndex());
                            } else {
                                Toast.makeText(getContext(), "该条目已经存在！", Toast.LENGTH_LONG).show();
                            }
                        } else {
                            while (cursor.moveToNext()) {
                                if (parentList.get(groupPosition).getName().equals(cursor.getString(cursor.getColumnIndex("first_title")))
                                        && insertContent.getText().toString().equals(cursor.getString(cursor.getColumnIndex("title")))) {
                                    isExist = true;
                                }
                            }
                            if (!isExist) {
                                values.put("first_title", parentList.get(groupPosition).getName());
                                values.put("title", insertContent.getText().toString());
                                db.insert(segment.getSelectedIndex() == 0 ? Constant.DATABASE_INCOME_SECOND_TABLE_NAME : Constant.DATABASE_EXPENSE_SECOND_TABLE_NAME,
                                        null, values);
                                toastMsg = "添加成功！";
                                createThread().start();
//                                Toast.makeText(getContext(), "添加成功！", Toast.LENGTH_LONG).show();
//                                onSegmentSelected(segment.getSelectedIndex());
                            } else {
                                Toast.makeText(getContext(), "该条目已经存在！", Toast.LENGTH_LONG).show();
                            }
                        }
                        cursor.close();
                        dialog.dismiss();
                    }
                } else {
                    Toast.makeText(getContext(), "输入不能为空！", Toast.LENGTH_LONG).show();
                }

            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.g1:
                list1.get(position).setIsCheck(!list1.get(position).isCheck());
                adapterList.get(0).notifyDataSetChanged();
                break;
            case R.id.g2:
                list2.get(position).setIsCheck(!list2.get(position).isCheck());
                adapterList.get(1).notifyDataSetChanged();
                break;
            case R.id.g3:
                list3.get(position).setIsCheck(!list3.get(position).isCheck());
                adapterList.get(2).notifyDataSetChanged();
                break;
            case R.id.g4:
                list4.get(position).setIsCheck(!list4.get(position).isCheck());
                adapterList.get(3).notifyDataSetChanged();
                break;
            case R.id.g5:
                if (position == list5.size() - 1) {
                    showInsertDialog(-1, false);
                    popupWindow.dismiss();
                } else {
                    list5.get(position).setIsCheck(!list5.get(position).isCheck());
                    adapterList.get(4).notifyDataSetChanged();
                }
                break;
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if (getAdapter().getEditable()) {
            showDeleteItemDialog(position);
        }
        return true;
    }

    private void showDeleteItemDialog(final int position) {
        dialog.show();
        window.setContentView(R.layout.dialog_delete_item);
        final TextView deleteContent = (TextView) window.findViewById(R.id.delete_content);
        deleteContent.setText(parentList.get(position).getName() + "及其子项");
        final Button confirm = (Button) window.findViewById(R.id.confirm);
        final Button cancel = (Button) window.findViewById(R.id.cancel);

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (segment.getSelectedIndex() == 0) {
                    db.delete(Constant.DATABASE_INCOME_FIRST_TABLE_NAME, "title = ?", new String[]{parentList.get(position).getName()});
                    db.delete(Constant.DATABASE_INCOME_SECOND_TABLE_NAME, "first_title = ?", new String[]{parentList.get(position).getName()});
                } else if (segment.getSelectedIndex() == 1) {
                    db.delete(Constant.DATABASE_EXPENSE_FIRST_TABLE_NAME, "title = ?", new String[]{parentList.get(position).getName()});
                    db.delete(Constant.DATABASE_EXPENSE_SECOND_TABLE_NAME, "first_title = ?", new String[]{parentList.get(position).getName()});
                }
                toastMsg = "删除成功！";
                createThread().start();

                dialog.dismiss();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    private Thread createThread(){
        return new Thread(){
            @Override
            public void run() {
                super.run();
                Message message = new Message();
                message.what = 0;
                mHandler.sendMessage(message);
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message message1 = new Message();
                message1.what = 1;
                mHandler.sendMessage(message1);
            }
        };
    }

    private MyHandler mHandler = new MyHandler();
    private static String toastMsg = "";

    public class MyHandler extends android.os.Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                progressBar.setVisibility(View.VISIBLE);
                onSegmentSelected(segment.getSelectedIndex());

            } else if (msg.what == 1) {
                progressBar.setVisibility(View.INVISIBLE);
                Toast.makeText(getContext(), toastMsg, Toast.LENGTH_LONG).show();
            }
        }
    }
}
